﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media;

namespace System.Windows.Media
{
    public static class ColorExtension
    {
        /// <summary>
        /// 使眼色减淡(不处理透明通道)
        /// </summary>
        /// <param name="color">当前颜色</param>
        /// <param name="rate">减淡/加深的比例,取值为(0-1]</param>
        /// <returns></returns>
        public static Color Shoal(ref this Color color, double rate)
        {
            if (rate <= 0)
            {
                throw new NotSupportedException("颜色减淡的比例必须大于0.");
            }
            if (rate > 1)
            {
                throw new NotSupportedException("颜色减淡的比例必须小于等于1.");
            }
            byte[] channels = new byte[] { color.R, color.G, color.B };
            int maxchannel = 0;//颜色值最大的通道索引
            byte maxChannelValue = 0;//颜色值最大的通道的值
            for (int i = 0; i < channels.Length; i++)
            {//计算值最大的通道
                if (channels[i] >= channels[maxchannel])
                {
                    maxchannel = i;
                    maxChannelValue = channels[i];
                }
            }
            for (int i = 0; i < channels.Length; i++)
            {
                if (i != maxchannel)
                {
                    channels[i] = (byte)Math.Min(channels[i] + ((maxChannelValue - channels[i]) * (1-rate)), maxChannelValue);
                }
            }
            return new Color() { R = channels[0], G = channels[1], B = channels[2], A = color.A };
        }
    }
}
